package cn.darkhorse.common.util;

import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用redis的list作为简单消息队列
 * @author yuanjun
 * @since 2023/2/3 11:09
 */
public class MsgUtil {
    public final static String warningKey = "msg:warning";
    public final static String auditKey = "msg:audit";

    /**
     * 发送消息
     * @param json
     * @return
     */
    public static Long sendWaringMsg(String json) {
        return MsgUtil.sendMsg(warningKey,json);
    }

    public static List<String> getWarningMsg() {
        return MsgUtil.getMsgAll(warningKey);
    }

    /**
     * 发送审核消息
     * @param json
     * @return
     */
    public static Long sendAuditMsg(String json) {
        return MsgUtil.sendMsg(auditKey,json);
    }

    public static List<String> getAuditMsg() {
        return MsgUtil.getMsgAll(auditKey);
    }

    private static Long  sendMsg(String key,String json) {
        RedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);
        return redisTemplate.opsForList().rightPush(key,json);
    }

    private static String getMsg(String key) {
        RedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);
        Object o = redisTemplate.opsForList().leftPop(key);
        return o == null? "" : o.toString();
    }

    /**
     * 根据key获取当前所有数据
     * @param key
     * @return
     */
    private static List<String> getMsgAll(String key) {
        RedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);
        List<String> o = redisTemplate.opsForList().range(key,0,-1);
        return o == null? new ArrayList<>() : o;
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值
     * @return 移除的个数
     */

    public static  long setRemove(String key, Object values) {
        RedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);
        try {
            Long count = redisTemplate.opsForList().remove(key,0,values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
